/*
	@file heap_gauss

	@brief Heap implementation by gauss

	@author gauss
*/
#ifndef __HEAP_GAUSS_H__
#define __HEAP_GAUSS_H__

#include<Windows.h>
#include<map>
#include"../../api/heap.h"

using namespace std;

/*
	enable to use standard malloc/realloc/free for testing correctness
	of complicated tests or comparing performance
*/
//#define _STUB

/*
	enable to redirect output to log file
*/
//#define _LOG

#define ALIGN 4*sizeof(int)//minimal blocks alignment

#define POISON_ALLOC 0xDEDEDEDE//debug poison for allocated pieces
#define POISON_FREE  0xABABABAB//debug poison for free pieces

/*
	Implementation of basic interface.
	Constructor throws bad_alloc exception if fails to get memory.
*/
class heap_gauss:public heap876
{
private://types
	struct MemoryBlock//structure for blocks of allocated memory
	{
		size_t size;
		unsigned int tag;
	};
	typedef map<void*,MemoryBlock>::iterator map_iterator;
	struct FitPlace//structure to be returned by first_fit()
	{
		void *ptr;
		map_iterator pos;
	};
private://fields
	void *Memory;//memory to be allocated
	size_t AllocatedSize;//current volume of distributed memory
	map<void*,MemoryBlock> Blocks;//map for matching adresses and blocks
	HANDLE Mutex;//mutex for synchronization
private://methods
	void free(map_iterator b);
	FitPlace first_fit(size_t sz);
public://methods
	heap_gauss(size_t total,alloc_flags flag);
	virtual ~heap_gauss();
	virtual void* alloc(size_t sz,unsigned int tag=0);
	virtual void free(void *ptr);
	virtual void free_all(unsigned int tag);
	size_t heap_gauss::get_occupancy()const
	{
		return(AllocatedSize);
	}
#ifdef _DEBUG//debugging stuff
	void dump_memory(void *ptr,size_t length);
	void dump_memory();
	void dump_block(void *ptr);
	void dump_all_blocks();
	void dump_memory_map(bool tags);
#endif//_DEBUG
};

#endif//__HEAP_GAUSS_H__
